export default class Tile {
    #tileElement; // tile元素
    #x: string | undefined; // 坐标
    #y: string | undefined; // 坐标
    #value: number | undefined;// 值：数字
    constructor(tileContainer: HTMLDivElement, value = Math.random() > 0.5 ? 2 : 4) {
        this.#tileElement = document.createElement("div");
        this.#tileElement.classList.add("tile");
        tileContainer.append(this.#tileElement);
        this.value = value;
    }

    set x(value: string) {
        this.#x = value;
        this.#tileElement.style.setProperty("--x", value);

    }
    set y(value: string) {
        this.#y = value;
        this.#tileElement.style.setProperty("--y", value);
    }

    get value() {
        return this.#value!;
    }

    set value(v: number) {
        this.#value = v;
        this.#tileElement.textContent = "" + v;
        const power = Math.log2(v); // 2的幂
        const backgroundLightness = 100 - power * 9;//value每增大一次，亮度减少9%
        this.#tileElement.style.setProperty("--background-lightness", `${backgroundLightness}%`);
        this.#tileElement.style.setProperty("--text-lightness", `${backgroundLightness <= 50 ? 90 : 10}%`);//根据亮度判断使用浅色还是深色

    }

    remove() {
        this.#tileElement.remove();
    }

    waitForTransition(animation=false) {
        return new Promise<void>(resolve => {
            this.#tileElement.addEventListener(animation?"animationend": 'transitionend', (e) => {
                resolve()
            }, { once: true })
        })
    }

}
